﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Passwords.Models;
using Passwords.Biz;

namespace Passwords.Pages
{
    /// <summary>
    /// Shows all categories to select for an existing password.
    /// </summary>
    public class ChangeCategoriesPicker : NewPasswordCategoriesPage
    {
        private PasswordItem passwordItem;

        #region props


        public PasswordItem PasswordItem
        {
            get { return passwordItem; }
            set
            {
                if (passwordItem != value)
                {
                    passwordItem = value;
                    OnPasswordItemChanged(value);
                }
            }
        }

        #endregion
        #region methods

        protected virtual void OnPasswordItemChanged(PasswordItem item)
        {
            controller.DataSource = GetSource();
        }


        protected override void OnSelect(object sender, EventArgs e)
        {
            Password password = passwordItem != null ? passwordItem.Password : null;
            if (password != null)
            {
                var categories = from s in Selection where s.IsSelected select s.Category;
                password.Categories = categories.ToList();
                GoBack();
            }
        }

        protected override IEnumerable<NewPasswordCategoriesPage.CategorySelection> GetSource()
        {
            Password password = passwordItem != null ? passwordItem.Password : null;
            if (password == null) return null;
            var source = base.GetSource();
            if (password != null)
            {
                foreach (var item in source)
                {
                    item.IsSelected = (password.Categories.Any(c => c.Id == item.Category.Id));
                }
            }
            return source;
        }

        #endregion

    }
}
